package com.zhyonk.controller;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.zhyonk.domain.AjaxResult;
import com.zhyonk.domain.ItemResultInfo;
import com.zhyonk.domain.StarUser;
import com.zhyonk.mapper.ItemListInfoMapper;
import com.zhyonk.mapper.ItemQueryInfoMapper;
import com.zhyonk.mapper.ItemResultInfoMapper;
import com.zhyonk.service.FaceService;
import com.zhyonk.service.TianxinService;
import com.zhyonk.util.PicUtils;
import org.json.JSONObject;
import com.zhyonk.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.bind.DatatypeConverter;
import java.util.*;

@Controller
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private IndexService indexService;

    @Autowired
    private ItemListInfoMapper itemListInfoMapper;

    @Autowired
    private ItemQueryInfoMapper itemQueryInfoMapper;

    @Autowired
    private ItemResultInfoMapper itemResultInfoMapper;

    @Autowired
    private FaceService faceService;

    @Autowired
    private TianxinService tianxinService;


    @RequestMapping(value = "/fixColorApi",produces = { "application/json;charset=UTF-8"})
    @ResponseBody
    public AjaxResult getIndexBaseInfo(@RequestBody HashMap<String, Object> param) {
        HashMap<String,Object> params = (HashMap<String, Object>) param.get("params");
        String base64 = "";
        if (Objects.isNull(params)){
            return AjaxResult.error("没有params");
        }

        Object base64Obj = params.get("base64");

        if (Objects.isNull(base64Obj)){
            return AjaxResult.error("没有base64");
        }
        base64 = base64Obj.toString();
        if (StrUtil.isBlank(base64)){
            return AjaxResult.error("图像出问题了");
        }

        base64 = base64.substring(22);
        double[] newSize = PicUtils.getNewSize(base64);
        Console.log("开始请求百度后台[上色]：" + System.currentTimeMillis());
        byte[] bytes = PicUtils.compressPicForScale(DatatypeConverter.parseBase64Binary(base64), 500,newSize);
        Console.log("结束请求百度后台[上色]：" + System.currentTimeMillis());
        base64 = Base64.getEncoder().encodeToString(bytes);

        JSONObject result = faceService.colourize(base64);

        if (result.has("error_code")){
            String errorCode = result.getInt("error_code") + "";
            if (StrUtil.isNotBlank(errorCode)){
                if ("216202".equals(errorCode)){
                    return AjaxResult.error("图片尺寸超过限制！");
                }
            }
        }
        AjaxResult success = AjaxResult.success();
        ItemResultInfo resultInfo = itemResultInfoMapper.selectById(Integer.parseInt(params.get("itemId").toString()));
        resultInfo.setResultImgBase64("data:image/png;base64," + result.getString("image"));
        success.put("resultInfo",resultInfo);
        return success;
    }

    @RequestMapping(value = "/queryStarFace",produces = { "application/json;charset=UTF-8"})
    @ResponseBody
    public AjaxResult queryStarFace(@RequestBody HashMap<String, Object> param) {
        HashMap<String,Object> params = (HashMap<String, Object>) param.get("params");
        String base64 = "";
        if (Objects.isNull(params)){
            return AjaxResult.error("没有params");
        }
        Object base64Obj = params.get("base64");
        if (Objects.isNull(base64Obj)){
            return AjaxResult.error("没有base64");
        }
        base64 = base64Obj.toString();
        if (StrUtil.isBlank(base64)){
            return AjaxResult.error("图像出问题了");
        }
        StarUser user = faceService.queryStarFace(base64);
        AjaxResult success = AjaxResult.success();
        ItemResultInfo resultInfo = itemResultInfoMapper.selectById(Integer.parseInt(params.get("itemId").toString()));

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("name","名称");
        hashMap.put("sex","性别");
        hashMap.put("constellation","爱好");
        hashMap.put("birthPlace","出生地");
        hashMap.put("birthDate","出生时间");
        hashMap.put("scoure","相似度");
        Map<String, Object>  entity = faceService.fillFieldEntity(user, hashMap);
        resultInfo.setInfoEntity(entity);
        resultInfo.setResultImgUrl(user.getImgUrl());
        resultInfo.setResEntity(user);
        success.put("resultInfo",resultInfo);
        return success;
    }

    @RequestMapping(value = "/getTopItemList",produces = { "application/json;charset=UTF-8"})
    @ResponseBody
    public AjaxResult getTopItemList(@RequestBody HashMap<String, Object> param) {
        Object itemIdObj = param.get("currItemId");
        Object categoryIdObj = param.get("categoryId");
        int itemId = -1;
        String msg = "";
        if (Objects.isNull(itemIdObj)){
            if (Objects.isNull(categoryIdObj)){
                return AjaxResult.error("缺乏参数");
            }
            return AjaxResult.success(indexService.getItemListByCategory(Integer.parseInt(categoryIdObj.toString())));
        }

        itemId = Integer.parseInt(itemIdObj.toString()); ;
        return AjaxResult.success(indexService.getTopItemList(itemId));
    }

    @RequestMapping(value = "/articleGen",produces = { "application/json;charset=UTF-8"})
    @ResponseBody
    public AjaxResult articleGen(@RequestBody HashMap<String, Object> param) {
        HashMap<String,Object> params = (HashMap<String, Object>) param.get("params");
        List<Map<String,Object>> inputList = null;
        if (Objects.isNull(params)){
            return AjaxResult.error("没有params");
        }

        Object inputListObj = params.get("inputList");
        if (Objects.isNull(inputListObj)){
            return AjaxResult.error("没有参数inputList");
        }
        inputList = (List<Map<String, Object>>) inputListObj;
        if (Objects.isNull(inputList)){
            return AjaxResult.error("参数有问题，转化异常");
        }
        ItemResultInfo resultInfo = itemResultInfoMapper.selectById(Integer.parseInt(params.get("itemId").toString()));
        String value = inputList.get(0).get("value").toString();
        String gen = tianxinService.articleGen(value);
        if (StrUtil.isBlank(gen)){
            return AjaxResult.error("查询失败，请输入2位以上的汉字");
        }
        String text = gen;
        //加入诗歌题目
        text = text.replace("，","，\n");
        text = text.replace("。","。\n");

        resultInfo.setResultText("《" + value +"》\n" + text);
        //将诗歌加入换行
        gen = gen.replace("，","，<br/>");
        gen = gen.replace("。","。<br/>");

        //加入诗歌题目
        gen = "《" + value +"》<br/>" + gen;

        resultInfo.setResultTextHtml(gen);
        AjaxResult success = AjaxResult.success();
        success.put("resultInfo",resultInfo);
        return success;
    }


}
